package com.jiaai.util.quartz;

import com.jiaai.util.DateTools;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import java.util.*;

/**
 * @Description:
 *
 * @Title: QuartzManager.java
 * @Package com.joyce.quartz
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-6-26 下午03:15:52
 * @version V2.0
 */
public class JobUtil {
    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();;
    private static final String JOB_GROUP_NAME = "jobGroup";
    private static final String TRIGGER_NAME = "trigger";
    private static final String TRIGGER_GROUP_NAME = "triggerGroup";

    //自定义初始化任务工厂
    public static void init(Properties props){
        try {
            schedulerFactory = new StdSchedulerFactory(props);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    //只执行一次
    public static void addSimpleJobExOnce(String jobName, Class jobClass, Map map) {
        try {
            String jobGroupName = JOB_GROUP_NAME.concat(jobName);
            String triggerName = TRIGGER_NAME.concat(jobName);
            String triggerGroupName = TRIGGER_GROUP_NAME.concat(jobName);
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名，任务组，任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            jobDetail.getJobDataMap().putAll(map);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            // 创建Trigger对象
            triggerBuilder.withSchedule(SimpleScheduleBuilder.simpleSchedule());
            SimpleTrigger trigger = (SimpleTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    //在某个时刻触发一次
    public static void addOnceJobByStrDate(String jobName, Class jobClass, Map map, String date){
        Date date1 = DateTools.strToDate(date);
        addOnceJobByDate(jobName, jobClass, map, date1);
    }
    /**
     * 在某个时刻触发一次
     * @param jobName
     * @param jobClass
     * @param map
     * @param date
     */
    public static void addOnceJobByDate(String jobName, Class jobClass, Map map, Date date){
        try {
            String jobGroupName = JOB_GROUP_NAME.concat(jobName);
            String triggerName = TRIGGER_NAME.concat(jobName);
            String triggerGroupName = TRIGGER_GROUP_NAME.concat(jobName);

            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名，任务组，任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            jobDetail.getJobDataMap().putAll(map);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startAt(date);
            // 触发器时间设定
            // 创建Trigger对象
            triggerBuilder.withSchedule(SimpleScheduleBuilder.simpleSchedule());
            SimpleTrigger trigger = (SimpleTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void addSimpleJob(String jobName, Class jobClass, int seconds
            , Map map) {
        try {
            String jobGroupName = JOB_GROUP_NAME.concat(jobName);
            String triggerName = TRIGGER_NAME.concat(jobName);
            String triggerGroupName = TRIGGER_GROUP_NAME.concat(jobName);
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名，任务组，任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            jobDetail.getJobDataMap().putAll(map);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            // 创建Trigger对象
            triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(seconds));
            SimpleTrigger trigger = (SimpleTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * @Description: 添加一个定时任务
     *
     * @param jobName 任务名
     * @param jobClass  任务
     * @param cron   时间设置，参考quartz说明文档
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void addJob(String jobName, Class jobClass, String cron
                                , Map map) {
        try {
            String jobGroupName = JOB_GROUP_NAME.concat(jobName);
            String triggerName = TRIGGER_NAME.concat(jobName);
            String triggerGroupName = TRIGGER_GROUP_NAME.concat(jobName);
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名，任务组，任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            jobDetail.getJobDataMap().putAll(map);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param cron   时间设置，参考quartz说明文档
     */
    public static void modifyJobTime(String jobName,
                                     String jobGroupName, String triggerName, String triggerGroupName, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /** 方式一 ：调用 rescheduleJob 开始 */
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 ：修改一个任务的触发时间
                sched.rescheduleJob(triggerKey, trigger);
                /** 方式一 ：调用 rescheduleJob 结束 */

                /** 方式二：先删除，然后在创建一个新的Job  */
                //JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                //Class<? extends Job> jobClass = jobDetail.getJobClass();
                //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);
                /** 方式二 ：先删除，然后在创建一个新的Job */
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一个任务
     *
     * @param jobName
     */
    public static void removeJob(String jobName) {
        try {
            String jobGroupName = JOB_GROUP_NAME.concat(jobName);
            String triggerName = TRIGGER_NAME.concat(jobName);
            String triggerGroupName = TRIGGER_GROUP_NAME.concat(jobName);

            Scheduler sched = schedulerFactory.getScheduler();

            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            sched.pauseTrigger(triggerKey);// 停止触发器
            sched.unscheduleJob(triggerKey);// 移除触发器
            sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void removeGroupjob(String jobName){
        try {
            String triggerName = TRIGGER_NAME.concat(jobName);
            Scheduler sched = schedulerFactory.getScheduler();

            GroupMatcher<TriggerKey> tg = GroupMatcher.triggerGroupContains(triggerName);
            sched.pauseTriggers(tg);
            List<TriggerKey> list = new ArrayList<TriggerKey>(sched.getTriggerKeys(tg));
            sched.unscheduleJobs(list);// 移除触发器

            GroupMatcher<JobKey> jg = GroupMatcher.groupContains(jobName);
            List<JobKey> jobs = new ArrayList<JobKey>(sched.getJobKeys(jg));
            sched.deleteJobs(jobs);// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:启动所有定时任务
     */
    public static void startJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
